<?php
/**
 * Class Export
 * 导出
 * @package app\common\lib
 */
class Export{

    public function __construct($keys, $vals, $name, $numFormat = [])
    {
        set_time_limit(0);
        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        foreach ($keys as $v) {
            $strTable .= '<td style="text-align:center;font-size:12px;width:*">'.$v.'</td>';
        }
        $strTable .= '</tr>';

        if (!empty($vals)) {
            foreach ($vals as $v) {
                $strTable .= '<tr>';
                foreach ($v as $kk=>$vv) {
                    if(in_array($kk, $numFormat)) {
                        $strTable .= '<td style="text-align:left;font-size:12px;vnd.ms-excel.numberformat:@">' . $vv . '</td>';
                    }else{
                        $strTable .= '<td style="text-align:left;font-size:12px;">' . $vv . '</td>';
                    }
                }
                $strTable .= '</tr>';
            }
        }
        $strTable .= '</table>';
        $this->downloadExcel($strTable, $name);
    }

    private function downloadExcel($strTable,$filename)
    {
        ob_end_clean();
        header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        header('Content-Type:application/vnd.ms-excel');
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=".$filename."_".date('Y-m-d').".xlsx");
        header('Expires:0');
        header('Pragma:public');
        echo '<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.$strTable.'</html>';
    }

}
